package com.zl.org.controller;

import com.zl.basic.annotation.PreAuthorize;
import com.zl.basic.util.AjaxResult;
import com.zl.basic.util.PageList;
import com.zl.org.domain.Department;
import com.zl.org.query.DepartmentQuery;
import com.zl.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    /**
     * 查询一个对象的数据
     * */
    @GetMapping("/{id}")
    @PreAuthorize(name = "查询单个对象",sn = "department:getOne")
    public Department findOne(@PathVariable("id")Long id){
        return departmentService.findById(id);
    }

    /**
     * 查询所有
     * */
    @GetMapping
    @PreAuthorize(name = "查询所有对象",sn = "department:getAll")
    public List<Department> findAll(){
        return  departmentService.findAll();
    }

    /**
     * 分页查询
     * */
    @PostMapping
    @PreAuthorize(name = "部门列表",sn = "department:list")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    /**
     * 删除操作
     * */
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "部门删除",sn = "department:delete")
    public AjaxResult del(@PathVariable("id")Long id){
        try {
            departmentService.remove(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败!");
        }
    }

    /**
     * 添加或者修改操作
     * */
    @PutMapping
    @PreAuthorize(name = "部门保存",sn = "department:save")
    public AjaxResult addORUpdate(@RequestBody Department department){
        try {
            if (department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
           return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败!!!");
        }
    }


    /**
     * 批量删除操作
     * */
    @PatchMapping
    @PreAuthorize(name = "批量删除",sn = "department:patchDelete")
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败!");
        }
    }

    @GetMapping("/deptTree")
    @PreAuthorize(name = "部门树",sn = "department:deptTree")
    public List<Department>deptTree(){
        return departmentService.deptTree();
    }


}
